<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\func\Constant;
use app\common\func\Lib;
use app\common\func\Libs;
use app\common\func\Tools;
use app\common\func\Transaction;
use app\common\func\WxPay;
use app\common\model\AllocationDetails;
use app\common\model\BalanceCopy;
use app\common\model\BalanceTotal;
use app\common\model\BalanceTotalCopy;
use app\common\model\CompanyStocks;
use app\common\model\Equip;
use app\common\model\EquipFigure;
use app\common\model\FlowSft;
use app\common\model\MoneyCash;
use app\common\model\MoneyFlow;
use app\common\model\MoneyLogs;
use app\common\model\Policy;
use app\common\model\PolicyProfit;
use app\common\model\StandardRecord;
use app\common\model\transaction\Hk;
use app\common\model\transaction\Jl;
use app\common\model\transaction\Sft;
use app\common\model\transaction\Xyf;
use app\common\model\WithdrawalOrder;
use fast\Http;
use fast\Random;
use fast\Rsa;
use LimitIterator;
use think\cache\driver\Redis;
use think\Db;
use think\Env;
use think\Exception;
use think\Hook;
use zjkal\ChinaHoliday;

class Test extends Api
{
    protected $noNeedLogin = ["*"];
    protected $noNeedRight = '*';

    public function import(){
        $url = "/uploads/mpos交易流水导出_20231219128754217_20231219-103527.xlsx";
        $fileData = Tools::importExcel($url);
        for($i = 1;$i < count($fileData);$i++){
            var_dump($fileData);exit;
        }
    }

    public function exports()
    {
        $baseUrl = "./trade_log/sft/";
        $fileName = "page.txt";

        if (!file_exists($baseUrl)) {
            mkdir($baseUrl, 0777, true);
        }

        if (!file_exists($baseUrl . $fileName)) {
            $pageInfo = ["page" => 1, "totalPage" => 0, "totalData" => 0];
            file_put_contents($baseUrl . $fileName, json_encode($pageInfo));
        }
        $pageInfo = json_decode(file_get_contents($baseUrl . $fileName), true);

        $base = ROOT_PATH . "public" . DS . "tenppostwo_data_202305_2.txt";

        $file = fopen($base, "r");

        $list = [];

        while (!feof($file)) {
            $line = fgets($file);
            $info = unserialize($line);
            $list[] = $info;
        }
        fclose($file);

        $list = new \ArrayIterator($list);

        if ($list->count() == 0) {
            exit;
        }

        $page = $pageInfo['page'];
        $pageSize = 100;
        $currentPage = $page <= 1 ? 0 : $page - 1;
        $offset = $currentPage * $pageSize;
        $totalPage = ceil($list->count() / $pageSize);

        if ($page == $totalPage) {
            file_put_contents($baseUrl . $fileName, json_encode(["page" => 1, "totalPage" => $totalPage, "totalData" => $list->count()]));
        } else {
            file_put_contents($baseUrl . $fileName, json_encode(["page" => $page + 1, "totalPage" => $totalPage, "totalData" => $list->count()]));
        }

        $pageData = new LimitIterator($list, $offset, $pageSize);
        foreach ($pageData as $key => $value) {
            $data = $value;
            $sn = $data['sn'];
            $equip = Lib::getEquip($sn);
            $order = Sft::where(["order_num" => $data['logNo']])->find();
            if ($equip && !$order) {
                try {
                    $orderNum = $data['logNo'];
                    $tranAmount = $data['txnAmt'];
                    $rate = ($data['mercFeeAmt'] && $data['txnAmt']) ? bcdiv((string)$data['mercFeeAmt'], (string)$tranAmount, 4) : 0;

                    $sft = new \app\common\model\transaction\Sft();
                    $sft->merchant_id = $data['mercId'];
                    $sft->order_num = $orderNum;
                    $sft->sn = $sn;
                    $sft->trading_time = strtotime($data['txnTm']);
                    $sft->transaction_amount = $tranAmount;
                    $sft->transaction_fee = $data['mercFeeAmt'];
                    $sft->transaction_rate = $rate * 100;
                    $sft->transaction_type = isset($data['txnCd']) ? $data['txnCd'] : 0;
                    $sft->card_type = isset($data['crdFlg']) ? $data['crdFlg'] : 0;
                    $sft->batch_no = isset($data['batchNo']) ? $data['batchNo'] : 0;
                    $sft->trace_no = isset($data['traceNo']) ? $data['traceNo'] : 0;
                    $sft->bank_type = isset($data['bnkTyp']) ? $data['bnkTyp'] : 0;
                    $sft->rate_type = isset($data['rateCd']) ? $data['rateCd'] : 0;
                    $sft->settle_type = isset($data['stlTyp']) ? $data['stlTyp'] : 0;
                    $sft->settle_time = strtotime($data['tmSmp']);
                    $sft->save();
                } catch (\Exception $e) {
                    file_put_contents($baseUrl . "sft_tran_log" . date("Ym") . ".txt", "-------------------" . date("Y-m-d H:i:s") . "-----------------" . PHP_EOL, FILE_APPEND | LOCK_EX);
                    file_put_contents($baseUrl . "sft_tran_log" . date("Ym") . ".txt", "data:" . json_encode($data) . PHP_EOL, FILE_APPEND | LOCK_EX);
                    file_put_contents($baseUrl . "sft_tran_log" . date("Ym") . ".txt", "error:" . $e->getMessage() . PHP_EOL, FILE_APPEND | LOCK_EX);
                }
            }
        }
    }

    //盛付通读取文件信息，写入设备绑定流程
    public function read()
    {
        $url = ROOT_PATH . "C:\Users\FdPro004\Desktop" . DS . "flow.txt";
        $file = fopen($url, "r");

        $list = [];

        while (!feof($file)) {
            $line = fgets($file);
            $info = json_decode($line, true);
            $list[] = $info;
//            if($info && count($info) > 0){
//                $list[] = [
//                    "sn" => $info['snNo'],
//                    "bindTm" => $info['bindTm'],
//                    "busTyp" => $info['busTyp'],
//                    "mercNm" => $info['mercNm'],
//                ];
//            }
        }
        fclose($file);

        foreach ($list as $key => $val) {
            if (is_array($val)) {
                $sn = $val['sn'];
                $data = $val;
                $equip = Lib::getEquip($val['sn']);
                if ($equip && $val['busTyp'] == 5) {
                    $figure = Lib::getFigureBySn($sn);
                    if (!$figure) {
                        $figure = new EquipFigure();
                        $figure->sn = $sn;
                    }

                    $figure->flow_status = 1;
                    $figure->save();

//                    $flow = Lib::getFlowSft($sn);
//                    if(!$flow){
//                        $obj = new FlowSft();
//                        $obj->order_num = $data['logNo'];
//                        $obj->trading_time = strtotime($data['txnTm']);
//                        $obj->sn = $sn;
//                        $obj->merchant_name = $data['mercNm'];
//                        $obj->flow_money = $data['txnAmt'];
//                        $obj->save();
//                    }
                }
            }
        }
    }

    public function test(){
        $rollbackUrl = Config("app_url")."/api/order/notifyRefund";//回调地址
        $refundNum = \app\common\func\Order::getOrderRefundNum();

        $wePay = new WxPay($rollbackUrl);
        $result = $wePay->refundOrder("4200002133202312149972306677",$refundNum,0.01);
        var_dump($result);exit;
    }

    public function test1()
    {
        exit;
        $list = Db::name("money_log")->alias("m")
            ->join("transaction_data_jl j","m.order_num = j.order_num","LEFT")
            ->field("m.money_type,j.transaction_amount,m.main_id,m.order_num,m.trading_time,m.sn,m.product_id,m.changes")
            ->select();
        foreach ($list as $key => $val){
            $level = Tools::getUserLevel($val['main_id']);
            if($val['money_type'] == "HX"){
                continue;
            }elseif ($val['money_type'] == "JG"){
                unset($level['AG']);
                unset($level['JG']);
            }elseif ($val['money_type'] == "AG"){
                unset($level['AG']);
            }
            $profit = Libs::getProfit(1,1,"0.6");

            $startProfit = 0;
            foreach ($level as $k => $v) {
                switch ($k){
                    case "HX":
                        $calculateRate = $profit->profit_profit + (float)Constant::$profitStep * 2;
                        $startProfit = $startProfit == 0 ? $val['changes'] :$startProfit ;
                        break;
                    case "JG":
                        $calculateRate = $profit->profit_profit + (float)Constant::$profitStep;
                        $startProfit = $startProfit == 0 ? $val['changes'] :$startProfit ;
                        break;
                    default:
                        $calculateRate = $profit->profit_profit;
                }

                $profitMoney = Transaction::roundNumber($val['transaction_amount'], $calculateRate);
                $diffMoney = $profitMoney - $startProfit;
                if($diffMoney > 0){
//                    Tools::saveMoney(2, $val['main_id'], 1, $k, $diffMoney, $val['sn'], $val['product_id'], "分润收益", ["table_name" => "transaction_data_jl", "order_num" => $val['order_num'], "tran_time" => $val['trading_time']]);
                }
                $startProfit = $profitMoney;
            }

        }
    }

    public function testHook()
    {
        Hook::add('test_hooks', function ($data) {
            file_put_contents("test_log.txt", "数据:" . json_encode($data) . PHP_EOL, FILE_APPEND | LOCK_EX);
        });

        $data = ["id" => 1];
        Hook::listen("test_hooks", $data);
        exit;
    }
}